import axios from "axios";
import cache from "@/utils/cache";

import { isString } from "./validate";
import { appVersion, apiHost, clickIdKeys } from "@/config";

axios.defaults.timeout = 30000;
// axios.defaults.withCredentials = true;
const service = axios.create({
  baseURL: apiHost,
  timeout: 30 * 1000,
});

// Request
service.interceptors.request.use(
  (config) => {
    let mpToken = cache.get("mpToken") || "";
    let click_id = cache.get("click_id") || "";
    const { url } = config;
    config.headers["version"] = appVersion;

    if (url.includes("mini")) {
      config.headers["token"] = mpToken;
    }
    if (url == "/open/ad/behavior" && mpToken) {
      config.headers["token"] = mpToken;
    }

    if (url == "/open/ad/submit" || url == "/mini/ad/submit") {
      config.baseURL = "https://api.iron.cchaosheng.com.com";
    }
    // console.log(config);
    if (config.params) {
      config.params.ad_url = window.location.href;
    }
		if(config.data){
			config.data.ad_url = window.location.href;
		}

    clickIdKeys.forEach((k) => {
      delete config.data?.[k];
      delete config.params?.[k];
    });
    if (click_id) {
      if (config.data) {
        config.data["click_id"] = click_id;
      }
      if (config.params) {
        config.params["click_id"] = click_id;
      }
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// Response
service.interceptors.response.use(
  (res) => {
    const { code, data, msg } = res.data;
    if (!res.data) {
      return res;
    }
    if (isString(res.data)) {
      return res.data;
    }
    if (code === 1) {
      return data;
    }
    return Promise.reject(msg);
  },
  async (error) => {
    if (error.response) {
      const { status, config, data } = error.response;
      console.error(status, config.url);

      switch (status) {
        case 400:
          return Promise.reject(data.msg);
        case 401:
          // await store.dispatch("userRemove");
          // href("/login");
          break;
        case 403:
          console.error(`${config.url} 无权限访问:)`);
          break;
        case 404:
          break;
        case 500:
          return Promise.reject("服务器内部错误:)");
        case 502:
          return Promise.reject("服务异常:)");
        default:
          console.error(status, config.url);
      }
      return Promise.reject(data.msg);
    }
    return Promise.reject(error.message);
  }
);

export default service;
